import {loginByUsername, getUserInfo, logout, } from '@/apis/index'
import {getToken, setToken, removeToken} from '@/utils/auth'
const API_RESULT = {
    SUCCESS: '000000',
    ERROR: '0600000',
    TOKEN_ERROR: '009010'
}
const user = {
    state: {
        token: getToken(),
        name: '',
        fontColor: '#ffffff',
        company: {},
        sys_flag: 0,
        activeRouter:'',
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_SYS_FLAG: (state, sys_flag) => {
            state.sys_flag = sys_flag
        },
        SET_AACTIVE_ROUTER: (state, activeRouter) => {
            state.activeRouter = activeRouter
        },
    },
    actions: {
        //  登录接口调用并存储token
        LoginByUsername({commit}, userInfo) {
            return new Promise((resolve, reject) => {
                loginByUsername().then(response => {
                    console.log(response)
                    if (response.dec.code == API_RESULT.SUCCESS) {
                        commit('SET_TOKEN', response.data.token);
                        commit('SET_NAME', response.data.name);
                        setToken(response.data.token)
                        resolve({code: 1});
                    } else {
                        resolve({code: 0, dec: response.dec});
                    }
                    resolve({code: 1, dec: response.dec});
                }).catch((error) => {
                    console.log(error)
                    reject(error);
                })
            })
        },
        // 获取用户信息
        GetUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(response => {
                    commit('SET_TOKEN', response.data.token);
                    commit('SET_NAME', response.data.name);
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 退出系统
        LogOut({commit, state}) {
            return new Promise((resolve, reject) => {
                // logout(state.token).then(() => {

                removeToken()
                commit('SET_TOKEN', '')
                commit('SET_NAME', '')
                commit('SET_SYS_FLAG', 1);
                //     state.token = ''
                resolve()
                // }).catch(error => {
                //     reject(error)
                // })
            })
        },
    }
}


export default user
